import { ref } from "vue";

import errorSoundPath from "~/assets/error.mp3";
import rightSoundPath from "~/assets/right.mp3";
import typingSoundPath from "~/assets/typing.mp3";
let rightAudio: HTMLAudioElement | null = null;
let errorAudio: HTMLAudioElement | null = null;
let typingSound: HTMLAudioElement | null = null;

if (typeof Audio !== "undefined") {
  rightAudio = new Audio(rightSoundPath);
  errorAudio = new Audio(errorSoundPath);
  typingSound = new Audio(typingSoundPath);
}

let lastPlayTime = 0;
const PLAY_INTERVAL = 100; // 设置播放间隔为100毫秒

export function usePlayTipSound() {
  function playRightSound() {
    rightAudio?.play();
  }

  function playErrorSound() {
    errorAudio?.play();
  }

  function playTypingSound() {
    const now = Date.now();
    if (now - lastPlayTime < PLAY_INTERVAL) return; // 如果距离上次播放时间小于间隔，则不播放
    lastPlayTime = now;

    if (typingSound) {
      typingSound.currentTime = 0; // 重置播放时间
      typingSound.play();
    }
  }

  return {
    playRightSound,
    playErrorSound,
    playTypingSound,
  };
}
